#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''
import logging
from pycommon import Const
from pycommon import Pack as packet
import GateManager
import CenterBuild
import ClientParse
import CounterManager

def cmdGateLogin(gate,pkt):
    logging.debug(u"gate login center")
    sid,ip,port = packet.unpack("HsH",pkt)
    valid = GateManager.instance.checkGateSidValid(sid)
    if valid:
        gate.onLogin(sid)
        GateManager.instance.gateLogin(sid,ip,port)
        gate.sendPacket(CenterBuild.gateLoginCenterSucess())
    else:
        logging.debug(u"sid=%d started,you can changed the sid and retry",sid)
        gate.kick()
    
def cmdTransPktGate2Ct(gate,pkt):
    uid,pid,cmd,opkt = packet.unpack("IHHs",pkt)
    logging.debug(u"Center RecvTransPkt uid = %d cmd = %d",uid,cmd)
    ClientParse.parse(gate,uid,pid,cmd,opkt)

def cmdReportCounter(gate,pkt):
    index = 0
    count = packet.unpack("H", pkt, index)
    index += 2
    logging.debug(u"cmdReportCounter(),login, count=%d", count)
    for i in range(count):
        counter, count = packet.unpack("Hi", pkt, index)
        index += 6
        #logging.debug(u"counter %d -> %d", counter, count)
        CounterManager.instance.addCount(counter, count)

def cmdReportOnline(gate,pkt):
    gateSid,count = packet.unpack("HH",pkt)
    GateManager.instance.updateOnline(gateSid,count)
    pass
#================================Ð­Òé±í===========================================
    
__cmdTable = {
                Const.CMD_GATE2CT_LOGIN          : cmdGateLogin,
                Const.CMD_GATE2CT_TRANS_PKT      : cmdTransPktGate2Ct,
                Const.CMD_GATE2CT_REPORT_COUNTER : cmdReportCounter,
                Const.CMD_GATE2CT_REPORT_ONLINE  : cmdReportOnline
             } 

def parse(gate, cmd, pkt):
    func = __cmdTable.get(cmd)
    if not func :
        logging.error(u"cmd is not exit");
    func(gate, pkt)    
    
if __name__ == '__main__':
    pass